#include "QTofelClient.h"

#include <QDebug>

QTofelClient::QTofelClient(QObject *parent) : BasicCaller(parent) {
}

QTofelClient::~QTofelClient() {
}

bool QTofelClient::start() {
    bool res = startProcess("cppSample.exe", {"configs/config.json"});
    if (res) {
        qDebug() << "[QTofel] Backed start";
    }
    return res;
}

bool QTofelClient::exit() {
    if (myProcess->state() == QProcess::Running) {
        if (!writeLine("x")) {
            return false;
        }
        if (!myProcess->waitForFinished(3000)) {
            qDebug() << "[QTofel] Backend is still alive, doing a force quit";
            if (!killProcess()) {
                notifyOnFailure("failed.to.shut");
                return false;
            }
        } else {
            qDebug() << "[QTofel] Backend quit";
        }
    }
    return true;
}

bool QTofelClient::inputOne() {
    return writeLine("1");
}

void QTofelClient::notifyProcessTerminated(int exitCode, QProcess::ExitStatus exitStatus) {
    qDebug().noquote() << QString::asprintf("[QTofel] Backend quit with code %d", exitCode);
}

void QTofelClient::notifyTextAvailable(const QString &line, QProcess::ProcessChannel channel) {
    qDebug() << line;
}
